package org.deng.vertx.springboot.config;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.DynamicTableNameInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import lombok.extern.slf4j.Slf4j;
import org.deng.vertx.common.util.SnowFlake;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;

/**

 * @Author DengLibin
 * @Desc mybatis plus 配置
 * @since 2020/3/12 0012 15:31
 */
@SpringBootConfiguration
@MapperScan(Constants.MAPPER_PACKAGE)
@Slf4j
public class MybatisPlusConfig {

    /**
     * 分页插件
     *
     * @return
     */
    // 最新版
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor(ProjectProperties projectProperties) {
        log.info("创建分页插件");
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        DbType dbType = DbType.MYSQL;
        if (projectProperties.getDbType() != null && projectProperties.getDbType().equals(org.deng.vertx.springboot.config.DbType.SHENTONG)) {
            dbType = DbType.ORACLE;//使用oracle的分页

            //神通数据库表名前加上模式名
            log.info("创建动态表名拦截器:{}", projectProperties.getSchema());
            DynamicTableNameInnerInterceptor innerInterceptor = new DynamicTableNameInnerInterceptor();
            innerInterceptor.setTableNameHandler((sql, tableName) -> projectProperties.getSchema() + "." + tableName);
            interceptor.addInnerInterceptor(innerInterceptor);
        }
        //分页插件
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(dbType));

        return interceptor;
    }
    /**
     * 雪花算法
     *
     * @param projectProperties
     * @return
     */
    @Bean
    public SnowFlake snowFlake(ProjectProperties projectProperties) {
        log.info("创建SnowFlake");
        return new SnowFlake((short) 1);
    }
    /**
     * id生成器
     *
     * @param snowFlake
     * @return
     */
    @Bean
    @Primary
    public IdGenerator idGenerator(SnowFlake snowFlake) {
        log.info("创建id生成器");
        return new IdGenerator(snowFlake);
    }
}
